#ifndef _RINGBUFFER_H_
#define _RINGBUFFER_H_
#include "dataIO.h"
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>

class RingBuffer {
private:
	size_t _size;
	size_t _mask;
	size_t _inIdx;
	size_t _outIdx;
	char* _buffer;
public:
	RingBuffer(size_t capacity) :
		_size(capacity),
		_mask(capacity-1),
		_inIdx(0),
		_outIdx(0)
	{
			_buffer = (char*)malloc(capacity);
	}

	~RingBuffer() {
		free(_buffer);
	}

	size_t available() {
		return (_inIdx-_outIdx) & _mask;
	}

	char peek() {
		return _buffer[_outIdx];
	}

	char read() {
		char result = _buffer[_outIdx];
		_outIdx = (_outIdx+1) & _mask;
		return result;
	}

	size_t freeSpace() {
		return (_outIdx-_inIdx - 1) & _mask;
	}

	void write(char data) {
		_buffer[_inIdx] = data;
		_inIdx = (_inIdx+1) & _mask;
	}

	void clear() {
		_inIdx = _outIdx = 0;
	}
};
#endif
